using System;
using System.Collections.Generic;
using PowerSearch.Core;
using System.Xml.Linq;
using System.Linq;
using PowerSearch.Utils.Helpers;

namespace PowerSearch.AppServices.Parser.Provider
{
	public class YahooParser : BaseFeedParser
	{
		public override string BaseUrl
		{
			get { return "http://rss.news.yahoo.com/rss/topstories"; }
		}

		internal protected override IList<Feed> ParseFeed(string responseData)
		{
			var feedList = new List<Feed>();
			var xmlDoc = XDocument.Parse(responseData);
			if (xmlDoc.Root != null)
			{
				var ns = xmlDoc.Root.GetDefaultNamespace();

				xmlDoc.Root.Descendants(ns+ "item").ToList().ForEach(element => feedList.Add(CreateFeedItem(element, ns)));
			}
			return feedList;
		}

		private Feed CreateFeedItem(XElement xElement, XNamespace ns)
		{
			var title = xElement.Element( ns+ "title") != null ? xElement.Element(ns+"title").Value : string.Empty;
			var description = xElement.Element(ns+"description") != null ? xElement.Element(ns+"description").Value : string.Empty;
			var clickUrl = xElement.Element(ns+"link") != null ? xElement.Element(ns+"link").Value : string.Empty;

			var feed = new Feed
			{
				Title = title,
				Description = CommonHelper.CleanUpDescription(description),
				ClickUrl = clickUrl,
				DisplayUrl = string.Empty
			};
			return feed;
		}
	}
}

